package rands

import (
	"math/rand"
	"time"
	"unsafe"
)

type Rands struct{}

func New() *Rands {
	return &Rands{}
}

// 生成随机字符
const (
	// letterBytes = "0123456789"
	// letterBytes   = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^&*"
	letterIdxBits = 7                    // 7 bits to represent a letter index
	letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
	letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
)

func (r *Rands) RandString(n int, letterBytes string) string {
	if letterBytes == "" {
		letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^&*"
	}
	src := rand.NewSource(time.Now().UnixNano())
	b := make([]byte, n)
	for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
		if remain == 0 {
			cache, remain = src.Int63(), letterIdxMax
		}
		if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
			b[i] = letterBytes[idx]
			i--
		}
		cache >>= letterIdxBits
		remain--
	}

	return *(*string)(unsafe.Pointer(&b))
}

// 生成随机数字
func (r *Rands) RandInt(min, max int) int {
	sjs := rand.New(rand.NewSource(time.Now().UnixNano()))
	return min + sjs.Intn(max-min+1)
}
